package com.stars.easyms.datasource.dynamic;

import com.stars.easyms.datasource.EasyMsDataSourceFactory;
import com.stars.easyms.datasource.properties.EasyMsDataSourceProperties;
import com.stars.easyms.base.util.ApolloListenUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * <p>className: DynamicLoadApolloConfig</p>
 * <p>description: 动态加载apollo配置类</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-05-30 09:51
 */
final class DynamicLoadApolloConfig {

    static void startListen(EasyMsDataSourceFactory easyMsDataSourceFactory, ApplicationContext applicationContext) {
        ApolloListenUtil.listen((ConfigurableApplicationContext) applicationContext, changeEvent -> {
            long filteredCount = changeEvent.changedKeys()
                    .stream()
                    .filter(key -> key.startsWith(EasyMsDataSourceProperties.MULTI_DATASOURCE_ACTIVE)
                            || key.startsWith(EasyMsDataSourceProperties.MULTI_DATASOURCE_ACTIVE_STANDBY)
                            || key.startsWith(EasyMsDataSourceProperties.DATASOURCE_NAME_PREFIX)).count();
            if (filteredCount > 0) {
                easyMsDataSourceFactory.loadMultiDataSource();
            }
        });
    }

    private DynamicLoadApolloConfig() {}

}